<template>
  <div>
    <div>
      <van-pull-refresh
        v-model="isRefreshLoading"
        @refresh="onRefresh"
        success
        success-text="加载成功"
        success-duration="1000"
      >
        <van-list
          class="article-list"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          :error.sync="error"
          error-text="请求失败，点击重新加载"
          @load="onLoad"
        >
          <ArticleItem
            v-for="(article, index) in artList"
            :key="index"
            :title="article.title"
            :art="article"
          />
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import { getArticleListApi } from '@/api/index.js'
// 引入 文章列表 组件
import ArticleItem from '@/components/Article-Item/ArticleItem.vue'
export default {
  name: 'contentList',
  data() {
    return {
      artList: [],
      error: false,
      loading: false,
      finished: false,
      timestamp: Date.now(),
      isRefreshLoading: false
    }
  },
  props: {
    channel: {
      require: true,
      type: Object
    }
  },
  components: { ArticleItem },
  created() {},
  methods: {
    async onLoad() {
      try {
        const { data } = await getArticleListApi(
          this.channel.id,
          this.timestamp || Date.now()
        )
        // 2. 把数据添加到 list 数组中
        const { results } = data.data
        this.artList.push(...results)
        // 3. 设置本次加载中 loading 状态结束
        this.loading = false
        // 4. 判断数据是否加载结束
        if (results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 没有数据了，设置加载状态结束，不再触发上拉加载更多了
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh() {
      try {
        const { data } = await getArticleListApi(this.channel.id, Date.now())
        // 2. 把数据添加到 list 数组中
        const { results } = data.data
        this.artList.unshift(...results)
        // 3. 设置本次加载中 loading 状态结束
        this.isRefreshLoading = false
        // 4. 判断数据是否加载结束
        if (results.length) {
          // 更新获取下一页数据的时间戳
        } else {
          // 没有数据了，设置加载状态结束，不再触发上拉加载更多了
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang='less' scoped>
</style>
